import SwiftUI
import UIKit

// 你需要先将 MjpegStreamingKit 源码拖入项目（如放在 Services 目录下）
// import MjpegStreamingKit  拖入源码后可取消注释

struct MJPEGPlayerView: UIViewRepresentable {
    let url: URL

    func makeUIView(context: Context) -> UIImageView {
        let imageView = UIImageView()
        imageView.contentMode = .scaleAspectFit
        let streamingController = MjpegStreamingController(imageView: imageView)
        streamingController.play(url: url)
        context.coordinator.streamingController = streamingController
        return imageView
    }

    func updateUIView(_ uiView: UIImageView, context: Context) {}

    func makeCoordinator() -> Coordinator {
        Coordinator()
    }

    class Coordinator {
        var streamingController: MjpegStreamingController?
    }
}

// 视频流显示视图
struct VideoStreamView: View {
    @EnvironmentObject var connectionSettings: ConnectionSettings
    @EnvironmentObject var tcpCarService: TCPCarService

    var body: some View {
        ZStack {
            if tcpCarService.isConnected {
                MJPEGPlayerView(url: URL(string: "http://\(connectionSettings.ipAddress):6500/video_feed")!)
                    .aspectRatio(16/9, contentMode: .fit)
                    .cornerRadius(12)
            } else {
                VStack {
                    Image(systemName: "video.slash.fill")
                        .font(.system(size: 40))
                        .foregroundColor(.white.opacity(0.8))
                    Text("视频流未连接")
                        .foregroundColor(.white)
                        .padding(.top, 8)
                }
                .padding()
                .background(Color.black.opacity(0.6))
                .cornerRadius(8)
            }
        }
    }
}

// 预览
struct VideoStreamView_Previews: PreviewProvider {
    static var previews: some View {
        VideoStreamView()
            .environmentObject(ConnectionSettings())
            .environmentObject(TCPCarService())
    }
} 
